//
//  YJ_TabBarView.m
//  YouJoin
//
//  Created by MacBookPro on 15/11/8.
//  Copyright © 2015年 MacBookPro. All rights reserved.
//

#import "YJ_TabBar.h"
#import "YJ_TabBarButton.h"
@interface YJ_TabBar()
//当前选中按钮
@property(nonatomic,weak)YJ_TabBarButton *selectedButton;

@end

@implementation YJ_TabBar

-(void)addTabButtonWithName:(NSString *)name selName:(NSString *)selName
{
    //创建
    YJ_TabBarButton *button = [YJ_TabBarButton buttonWithType:UIButtonTypeCustom];
    //设置背景图片
    [button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:selName] forState:UIControlStateSelected];
    //添加
    [self addSubview:button];
    
#pragma 监听点击
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}

//位置设置
- (void)layoutSubviews
{
    [super layoutSubviews];

    int count = self.subviews.count;
    for (int i = 0; i<count; i++) {
        YJ_TabBarButton *button = self.subviews[i];
        button.tag = i;

        // 设置frame
        CGFloat buttonY = 0;
        CGFloat buttonW = self.frame.size.width / count;
        CGFloat buttonH = self.frame.size.height;
        CGFloat buttonX = i * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        button.backgroundColor = [UIColor blackColor];
        button.alpha = 0.8;
//        button.imageView.frame = CGRectMake(buttonX, buttonY, 1, 1);
        button.contentMode = UIViewContentModeScaleAspectFit;
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
}


//监听按钮点击
- (void)buttonClick:(YJ_TabBarButton *)button
{
    // 0.通知代理
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectButtonFrom:to:)]) {
        [self.delegate tabBar:self didSelectButtonFrom:self.selectedButton.tag to:button.tag];
    }
    
    // 1.让当前选中的按钮取消选中
    self.selectedButton.selected = NO;
    
    // 2.让新点击的按钮选中
    button.selected = YES;
    
    // 3.新点击的按钮就成为了"当前选中的按钮"
    self.selectedButton = button;
}


@end